package com.wf.juc.forkjoin;

import lombok.Getter;
import lombok.Setter;

import java.util.concurrent.*;

/**
 * 功能描述
 *
 * @author wf
 * @since 2022/8/3
 */
@Setter
@Getter
public class AccumulateTask extends RecursiveTask<Integer> {
    private static final int THRESHOLD = 2;

    private int start;

    private int end;

    public AccumulateTask(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected Integer compute() {
        int sum = 0;
        boolean canCompute = end - start <= THRESHOLD;
        if (canCompute) {
            for (int i = start; i <= end; i++) {
                sum += i;
            }
            System.out.println("达到执行条件，任务直接执行");
        } else {
            System.out.println("任务过大，一分为二");

            int mid = (end + start) / 2;
            // 切割为两个子任务
            AccumulateTask lTask = new AccumulateTask(start, mid);
            AccumulateTask rTask = new AccumulateTask(mid + 1, end);
            lTask.fork();
            rTask.fork();

            Integer lRet = lTask.join();
            Integer rRet = rTask.join();

            sum = lRet + rRet;
        }

        return sum;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        ForkJoinPool forkJoinPool = new ForkJoinPool();
        //创建一个累加任务，计算由1加到10
        AccumulateTask countTask = new AccumulateTask(1, 100);
        Future<Integer> future = forkJoinPool.submit(countTask);

        Integer sum = future.get(1, TimeUnit.SECONDS);

        //预期的结果为5050
        System.out.println("ret is " + sum);
    }
}
